import base64
import random

from django.shortcuts import render

# Create your views here.
from uuid import uuid4

from rest_framework.response import Response
from rest_framework.views import APIView

from middlewares.auth import user_status_middleware
from utils.image_cache import DrawCache, CutImageCache
from utils.my_redis import get_image_cache, save_image_cache, save_image_cache_success
from utils.qrcode_cache import build_qrcode


class ImageCacheView(APIView):
	"""图形验证码模型"""

	@user_status_middleware
	def get(self, request):
		"""get接口"""
		mode = request.META.get('user_status')
		ck = request.GET.get('ck', None)
		offset = 5 if mode == "2" else 12
		uuid = ""
		if ck:
			x = request.GET.get('offset_x', None)
			y = request.GET.get('offset_y', None)
			if x and y:
				success_position_x, success_position_y, status_ = self.get_position(ck)
				if status_:
					if success_position_x-offset <= int(x) <= success_position_x + offset and success_position_y-offset <= int(y) <= success_position_y + offset:
						message = "success"
						code = 200
						uuid = str(uuid4())
						save_image_cache_success(uuid=uuid)
					else:
						message = "验证失败"
						code = 3001
				else:
					message = "验证失败"
					code = 3001
			else:
				message = "验证失败"
				code = 3001
			# 验证是否合法
			return Response({"message": message, "code": code, "uuid": uuid})
		else:
			# 生成ck
			# image_base = CutImageCache if mode == "1" else DrawCache
			image_base = CutImageCache
			w = random.choice([160, 200, 200, 200, 200, 240])
			cut_image = image_base(w=w, h=w)
			cache_uuid = str(uuid4())
			image_byte, possible_position, text = cut_image.get_one()
			save_image_cache(uuid=cache_uuid, x=possible_position[0], y=possible_position[1])
			image_byte = base64.b64encode(image_byte).decode()
			return Response({"label1": image_byte, "label2": cache_uuid, "label3": "", "label4": w, "label5": w})

	def get_position(self, ck):
		return get_image_cache(uuid=ck)


def page_not_found(request, *args, **kwargs):
	return render(request, '404.html')
